import React, { useState } from'react';
import { fetchAIAsswer } from '../../services/chat'; // 替换为实际接口请求文件路径
import './Service.css'; // 需创建对应的 CSS 文件

const ChatPage = () => {
  const [inputValue, setInputValue] = useState('');
  const [messages, setMessages] = useState([
    {
      role: 'assistant',
      content: '你好呀～我是你的 AI 助手，有什么问题可以问我～',
    },
  ]);
  const [isLoading, setIsLoading] = useState(false);

  const handleSend = async () => {
    if (!inputValue.trim()) return;

    // 添加用户消息
    setMessages((prev) => [
     ...prev,
      {
        role: 'user',
        content: inputValue,
      },
    ]);
    setIsLoading(true);
    setInputValue('');

    try {
      // 调用 AI 接口获取回答
      const aiResponse = await fetchAIAsswer(inputValue);
      // 添加 AI 回答
      setMessages((prev) => [
       ...prev,
        {
          role: 'assistant',
          content: aiResponse,
        },
      ]);
    } catch (error) {
      setMessages((prev) => [
       ...prev,
        {
          role: 'assistant',
          content: '抱歉，获取回答失败，请稍后再试～',
        },
      ]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="chat-page">
      <div className="chat-header">
        <h2>AI 聊天助手</h2>
      </div>
      <div className="chat-messages">
        {messages.map((msg, index) => (
          <div
            key={index}
            className={`message ${msg.role === 'user'? 'user' : 'assistant'}`}
          >
            <div className="message-content">{msg.content}</div>
          </div>
        ))}
        {isLoading && (
          <div className="message assistant loading">
            <div className="loading-dot"></div>
            <div className="loading-dot"></div>
            <div className="loading-dot"></div>
          </div>
        )}
      </div>
      <div className="chat-input">
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="请输入消息..."
        />
        <button onClick={handleSend} disabled={isLoading}>
          发送
        </button>
      </div>
    </div>
  );
};

export default ChatPage;